package com.lcredu.lcrspringboot;

import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.File;

/**
 * @author 黎长容
 * @date 2025-08-10 19:05
 */
public class LcrApplication {

    public static void run() {
        Tomcat tomcat = new Tomcat();

        try {
            // 明确设置连接器和端口
            Connector connector = new Connector();
            connector.setPort(9090);
            tomcat.setConnector(connector);

            //让 tomcat 可以将请求转发到 spring web 容器, 因此需要关联一把
            //1. /hspboot 就是 tomcat 的 applicaton context
            //理解为工程路径, D:\\hsp.... 就是这个工程的路径
            tomcat.addWebapp("/lcrboot", "D:\\Code\\JavaCode\\Spring\\springboot\\lcr_springboot");
            
            // 设置基础目录
            String tempDir = System.getProperty("java.io.tmpdir");
            tomcat.setBaseDir(tempDir);

            // 添加Web应用上下文
            Context context = tomcat.addContext("", new File(tempDir).getAbsolutePath());

            // 添加测试Servlet
            Tomcat.addServlet(context, "helloServlet", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                        throws IOException {
                    resp.setContentType("text/html;charset=UTF-8");
                    resp.getWriter().println("<h1>Hello from Embedded Tomcat!</h1>");
                    resp.getWriter().println("<p>服务器正在端口9090上运行</p>");
                }
            });
            context.addServletMappingDecoded("/hello", "helloServlet");

            // 添加默认Servlet处理根路径
            Tomcat.addServlet(context, "defaultServlet", new org.apache.catalina.servlets.DefaultServlet());
            context.addServletMappingDecoded("/", "defaultServlet");

            // 启动Tomcat
            System.out.println("正在启动Tomcat服务器...");
            tomcat.start();
            System.out.println("Tomcat服务器启动成功，监听端口: 9090");
            System.out.println("访问地址:");
            System.out.println("  http://localhost:9090/hello - 测试页面");
            System.out.println("  http://localhost:9090/ - 默认页面");

            // 验证端口状态
            verifyPort(9090);

            // 保持服务器运行
            tomcat.getServer().await();

        } catch (Exception e) {
            System.err.println("启动Tomcat时发生错误:");
            e.printStackTrace();
        } finally {
            try {
                if (tomcat.getServer() != null && tomcat.getServer().getState() != null) {
                    tomcat.stop();
                    tomcat.destroy();
                }
            } catch (Exception e) {
                System.err.println("关闭Tomcat时发生错误:");
                e.printStackTrace();
            }
        }
    }

    private static void verifyPort(int port) {
        try (java.net.ServerSocket socket = new java.net.ServerSocket(port)) {
            System.out.println("警告：端口" + port + "未被Tomcat占用");
        } catch (java.net.BindException e) {
            System.out.println("确认：端口" + port + "已被Tomcat占用并监听");
        } catch (Exception e) {
            System.out.println("检查端口时发生错误: " + e.getMessage());
        }
    }
}
